package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.codahale.metrics.annotation.Timed;
import com.landinfo.config.ArcGISAttamentUploadProperties;
import org.apache.tools.ant.types.selectors.FilenameSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * Created by ziqilv on 2019/01/16.
 * Arcgis Attachments 附件上传
 */
@RestController
@RequestMapping("/api")
public class ArcGISAttachmentsResource {

    private final Logger log = LoggerFactory.getLogger(ArcGISAttachmentsResource.class);

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ArcGISAttamentUploadProperties arcGISAttamentUploadProperties;

    public ArcGISAttachmentsResource() {

    }

    /**
     * 文件上传具体实现方法;
     *
     * @param files
     * @return
     */
    @PostMapping("/attachment/arcgis/upload")
    @Timed
    public String attachmentUpload(@RequestParam(value = "files",required = false) MultipartFile[] files, @RequestParam(value = "path",required = false) String path) {
        log.debug("upload start");
        HashMap<String, Object> result = new HashMap<>();
        List<Integer> successList = new ArrayList<>();
        if(files.length > 0){
            for(int i=0; i < files.length; i++){
                MultipartFile file = files[i];
                if (!file.isEmpty()) {
                    try {
                        String oldFileName = file.getOriginalFilename();
                        String newFileName = UUID.randomUUID().toString() + oldFileName.substring(oldFileName.lastIndexOf("."));
                        if (arcGISAttamentUploadProperties.getReplacePicturePath1() != null && !"".equals(arcGISAttamentUploadProperties.getReplacePicturePath1())) {
                            path = path.replace(arcGISAttamentUploadProperties.getReplacePicturePath1(), arcGISAttamentUploadProperties.getReplacePicturePath2());
                        }
                        File tempFile = new File(path);
                        if (!tempFile.exists()) {
                            tempFile.mkdirs();
                        }
                        // todo 将前台传回来的地址的分隔符换位后台的File.separator

                        File newFile = new File(path + File.separator + newFileName);
                        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
                        out.write(file.getBytes());
                        out.flush();
                        out.close();
                        successList.add(i);
//                        return newFileName;
                        //return ImageHelper.fileToBase64(newFile.getPath());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
//                        return "上传失败," + e.getMessage();
                    } catch (IOException e) {
                        e.printStackTrace();
//                        return "上传失败," + e.getMessage();
                    } catch (Exception e) {
                        e.printStackTrace();
//                        return "上传失败," + e.getMessage();
                    }
                }
            }
        }
        result.put("success", successList);
        return JSON.toJSONString(result);
    }

    @PostMapping("/attachment/arcgis/getpictures")
    @Timed
    public String getPictureNameByPath(@RequestParam String path) {
        if (arcGISAttamentUploadProperties.getReplacePicturePath1() != null && !"".equals(arcGISAttamentUploadProperties.getReplacePicturePath1())) {
            path = path.replace(arcGISAttamentUploadProperties.getReplacePicturePath1(), arcGISAttamentUploadProperties.getReplacePicturePath2());
        }
        File tempFile = new File(path);
        if (!tempFile.exists()) {
            return null;
        }
        File[] files = tempFile.listFiles();
        HashMap<String, Object> results = new HashMap<>();
        List<String> resultFileNames = new ArrayList<>();
        for (File file : files) {
            if (file.getName().contains(".")) {
                resultFileNames.add(file.getName());
            }
        }
        results.put("pictures", resultFileNames);
        results.put("path", path.replace(arcGISAttamentUploadProperties.getGreenPicturePath(), "").replace("\\", "/"));
        return JSON.toJSONString(results);
    }

    @PostMapping("/attachment/arcgis/delpictures")
    @Timed
    public String delPictureNameByPath(@RequestParam String path, @RequestParam String filename) {
        HashMap<String, Object> result = new HashMap<>();
        if (arcGISAttamentUploadProperties.getReplacePicturePath1() != null && !"".equals(arcGISAttamentUploadProperties.getReplacePicturePath1())) {
            path = path.replace(arcGISAttamentUploadProperties.getReplacePicturePath1(), arcGISAttamentUploadProperties.getReplacePicturePath2());
        }
        File tempFile = new File(path + File.separator + filename);
        if (!tempFile.exists()) {
            result.put("success", false);
            return JSON.toJSONString(result);
        }
        tempFile.delete();
        result.put("success", true);
        return JSON.toJSONString(result);
    }

}
